package com.servlet;

import com.cloopen.rest.demo.SDKTestSendTemplateSMS;
import com.entity.DinerUser;
import com.entity.dto.ApiResult;
import com.service.DinerUserService;
import com.utils.UserUtil;
import org.springframework.beans.NullValueInNestedPathException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RequestMapping
@RestController
@CrossOrigin
public class DinerUserServlet {

    @Autowired
    DinerUserService service;

    @RequestMapping("getUserInfo")
    public ApiResult getUserInfo(String userPhone) {
        DinerUser user = new DinerUser();
        user = service.getUserInfo(userPhone, null);
        if (user == null) {
            return new ApiResult(500, "用户不存在", "String", null);
        }
        if (user.getId() != null) {
            String MD5 = user.getUser_phone() + System.currentTimeMillis();
            String token = DigestUtils.md5DigestAsHex(MD5.getBytes());
            try (Jedis jedis = new Jedis("47.106.226.199", 6429)) {
                jedis.auth("666t01");
                jedis.setex(token, 60 * 1000, String.valueOf(user.getId()));
            }
            Map map = new HashMap();
            map.put("token", token);
            map.put("timeout", (60 * 5) + "000");
            return new ApiResult(200, "ok", "Object", map);
        }

        return new ApiResult(500, "失败", "String", null);
    }

    @RequestMapping("captcha")
        public ApiResult getCaptcha(String userPhone) {
        DinerUser user = new DinerUser();
        if(userPhone==null || userPhone.equals("")){
            return new ApiResult(500, "手机号不能为空", "String", null);
        }
        user = service.getUserInfo(userPhone, null);
        if (user == null) {
            return new ApiResult(500, "用户不存在", "String", null);
        }else {
            SDKTestSendTemplateSMS.getMsgSend(userPhone);
        }
        return new ApiResult(200, "ok", "String",null);

    }

    @RequestMapping("getUserData")
    public ApiResult getUserData(HttpServletRequest request) {
        DinerUser user = new DinerUser();
        user = service.getUserInfo(null, UserUtil.getUserId(request));
        return new ApiResult(200, "ok", "Object", user);
    }
}
